#include "shmem.h"

/*
	Sender function
	Initialises all Ressources and sends signs one by one
	EOF problem is solved with using ints intstead of chars, to use additional EOF value
	Cleanup at the end to remove all used ressources
*/

int main (int argc, char *argv[])
{
    /* Buffer of SHM */
    int shm_buffer = 0;

    /* Char as int representation, to include EOF */
    int input_sign = -1;
 
    /* Check and Convert Command Line Parameters */
    if ((shm_buffer = CheckParams(argc, argv)) == ERROR) 
		return ERROR;
 
    /* Initialises ressources (SHM, Semaphores) */
    if (InitResources(SENDER, shm_buffer) == ERROR) 
		return ERROR;
 
	/* Start to write to shared memory */
    do 
	{
        /* Read a char from stdin */
        input_sign = fgetc(stdin);
         
        /* Wait for the write semaphore */
        if (WaitForSemaphore() == ERROR) 
			return ERROR;
 
        /* Write to SHM */
        WriteToSharedMemory(input_sign);
 
        /* Signal to read Semaphore */
        if (SignalToSemaphore() == ERROR) 
			return ERROR;

    } while (input_sign != EOF);

    /* Check for Input error or EOF */
    if (ferror(stdin)) 
	{
        handle_errno("Error Reading from stdin!");
        return ERROR;
	}

    /* Cleanup (SHM, Semaphores) and return exit state */
    if (clean_up(SEM_R_KEY) == -1) 
      return ERROR;
    else                            
      return OKAY;
}
